<?php
namespace app\Logic\Layui\Service;

use app\Logic\Factory;
use app\Logic\Layui\ServiceProviders\AdminUser;
use app\Logic\Logic;
use Illuminate\Support\Facades\DB;
use Validator;

class AdminLogin extends Logic implements ServiceInterface
{
    public $app;

    public function __construct(AdminUser $app)
    {
        $this->app = $app;
    }


    /**
     * @param string $username
     * @param string $password
     * @param string $code
     * @return \Illuminate\Http\JsonResponse
     */
    public function login(string $username, string $password, string $code)
    {
        $data = [
            'username' => $username,
            'password' => $password,
        ];
        $rules = array(
            'username'=>'required|alpha_num|max:10|min:4',
            'password' => 'required|alpha_dash|max:20|min:6',
        );

        $validator = Validator::make($data, $rules);
        if (!$validator->passes()) {

            $msg = array_reduce($validator->errors()->all(),function ($v1 , $v2){
                return $v1 ."\n". $v2;
            },'');

            return $this->fail('ERROR' , $msg);
        }

        if(strtolower($code) !== strtolower(session('imgCode'))){
            //return $this->fail('ERROR' , '验证码错误');
        }

        $user = DB::table('admin_user')->where(['username'=>$username])->first();

        if(!$user) {
            return $this->fail('ERROR' , '该用户不存在');
        }

        if($user->status == 0){
            return $this->fail('ERROR' , '该用户已被禁用');
        }

        $app = Factory::Layui();

        $encryptPassword = $app->AdminUser(function ($app){
            return new Register($app);
        })->encryptPassword($password , $user->salt);

        if($encryptPassword !== $user->password) {
            return $this->fail('ERROR' , '密码错误');
        }

        DB::beginTransaction();
        try {
            $app->Loger(function ($app){
                return new ActionLog($app);
            })->write($user->id);

            DB::table('admin_user')->where(['id'=>$user->id])->update([
                'last_login_ip' => '127.0.0.1',
                'last_login_time' => date('Y-m-d H:i:s'),
                'updated_at' => date('Y-m-d H:i:s'),
            ]);

            session(['adminId' => $user->id]);

            DB::commit();
            return $this->success();

        } catch(\Illuminate\Database\QueryException $ex) {

            DB::rollback();
            return $this->fail('ERROR' , $ex->getMessage());

        } catch(\Exception $ex) {

            DB::rollback();
            return $this->fail('ERROR' , $ex->getMessage());
        }

    }
}